require 'osx/cocoa'
include OSX

class GraphView < NSView
  ib_outlet :controller
  
  def update
    setNeedsDisplay(true)
  end
  
  def drawRect(rect)
    NSColor.blackColor.set
    NSRectFill(bounds)
    
    drawLines
    
    path = NSBezierPath.alloc.init
    path.setLineWidth 2
    
    path.moveToPoint(PointToNSPoint(@controller.origin))
    path.lineToPoint(PointToNSPoint(@controller.origin + @controller.vector.point))
    
    @controller.color.set
    path.stroke
  end
  
  def drawLines
    NSColor.blueColor.set
    
    # Start with the X axis
    path = NSBezierPath.alloc.init
    path.setLineWidth 2
    path.moveToPoint NSMakePoint(0, 1)
    path.lineToPoint NSMakePoint(bounds.width, 1)
    path.stroke
    
    0.upto(bounds.width) do |x|
      if x % 10 == 0
        path.setLineWidth x % 50 ? 2 : 4
        path.moveToPoint NSMakePoint(x, 0)
        path.lineToPoint NSMakePoint(x, bounds.height)
        path.stroke
      end
    end
    
    # And then the Y
    path.setLineWidth 2
    path.moveToPoint NSMakePoint(1, 0)
    path.lineToPoint NSMakePoint(1, bounds.height)
    path.stroke
    
    0.upto(bounds.height) do |y|
      if y % 10 == 0
        path.setLineWidth = (y % 50 == 0) ? 2 : 4
        path.moveToPoint NSMakePoint(0, bounds.height)
        path.lineToPoint NSMakePoint(bounds.width, y)
        path.stroke
      end
    end
  end
  
  def drawAxes(direction, limit)
  
  def acceptsFirstResponder
    true
  end
  
  def mouseDown(event)
    loc = convertPoint_fromView(event.locationInWindow, nil)
    @controller.origin = NSPointToPoint(loc)
    @controller.vector = Vector.new(@controller.vector.length, @controller.vector.angle)
    NSLog("Origin set to #{@controller.origin}")
    
    update
  end
  
  def PointToNSPoint(p)
    NSMakePoint(p.x.round, p.y.round)
  end
  
  def NSPointToPoint(p)
    Point.new(p.x, p.y)
  end
end